// src/pages/VMDetail/HardwareTab.tsx
import React, { useState } from 'react';
import {
  Card,
  Descriptions,
  Button,
  Space,
  Modal,
  Form,
  InputNumber,
  message,
  Divider,
  Row,
  Col,
} from 'antd';
import {
  EditOutlined,
  CpuOutlined,
  MemoryOutlined,
  HddOutlined,
  ApiOutlined,
} from '@ant-design/icons';
import type { Domain } from '../../api/types';
import { useDomainStore } from '../../stores/domainStore';
import { domainsApi } from '../../api/domains';

interface HardwareTabProps {
  domain: Domain;
}

const HardwareTab: React.FC<HardwareTabProps> = ({ domain }) => {
  const { fetchDomain } = useDomainStore();
  const [cpuModalVisible, setCpuModalVisible] = useState(false);
  const [memoryModalVisible, setMemoryModalVisible] = useState(false);
  const [form] = Form.useForm();

  const handleUpdateCPU = async (values: { vcpus: number }) => {
    try {
      await domainsApi.setVCPUs(domain.name, values.vcpus);
      message.success('CPU 配置已更新');
      setCpuModalVisible(false);
      await fetchDomain(domain.name);
    } catch (error) {
      message.error('更新失败');
    }
  };

  const handleUpdateMemory = async (values: { memory: number }) => {
    try {
      await domainsApi.setMemory(domain.name, values.memory);
      message.success('内存配置已更新');
      setMemoryModalVisible(false);
      await fetchDomain(domain.name);
    } catch (error) {
      message.error('更新失败');
    }
  };

  return (
    <div style={{ padding: '16px' }}>
      <Row gutter={[16, 16]}>
        {/* CPU 配置 */}
        <Col span={12}>
          <Card
            title={
              <Space>
                <CpuOutlined />
                CPU 配置
              </Space>
            }
            extra={
              <Button
                type="link"
                icon={<EditOutlined />}
                onClick={() => {
                  form.setFieldsValue({ vcpus: domain.vcpus });
                  setCpuModalVisible(true);
                }}
                disabled={domain.state === 'running'}
              >
                编辑
              </Button>
            }
          >
            <Descriptions column={1}>
              <Descriptions.Item label="虚拟 CPU 数量">
                {domain.vcpus}
              </Descriptions.Item>
              <Descriptions.Item label="CPU 模式">host-passthrough</Descriptions.Item>
              <Descriptions.Item label="CPU 拓扑">
                1 socket, {domain.vcpus} cores, 1 thread
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>

        {/* 内存配置 */}
        <Col span={12}>
          <Card
            title={
              <Space>
                <MemoryOutlined />
                内存配置
              </Space>
            }
            extra={
              <Button
                type="link"
                icon={<EditOutlined />}
                onClick={() => {
                  form.setFieldsValue({ memory: domain.memory });
                  setMemoryModalVisible(true);
                }}
                disabled={domain.state === 'running'}
              >
                编辑
              </Button>
            }
          >
            <Descriptions column={1}>
              <Descriptions.Item label="当前内存">
                {(domain.memory / 1024).toFixed(1)} GB
              </Descriptions.Item>
              <Descriptions.Item label="最大内存">
                {(domain.max_memory / 1024).toFixed(1)} GB
              </Descriptions.Item>
              <Descriptions.Item label="内存类型">DIMM</Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>

        {/* 存储设备 */}
        <Col span={12}>
          <Card
            title={
              <Space>
                <HddOutlined />
                存储设备
              </Space>
            }
            extra={
              <Button type="link" icon={<EditOutlined />} disabled>
                编辑
              </Button>
            }
          >
            <Descriptions column={1}>
              <Descriptions.Item label="磁盘 1">
                /var/lib/libvirt/images/{domain.name}.qcow2
              </Descriptions.Item>
              <Descriptions.Item label="总线类型">virtio</Descriptions.Item>
              <Descriptions.Item label="缓存模式">writeback</Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>

        {/* 网络设备 */}
        <Col span={12}>
          <Card
            title={
              <Space>
                <ApiOutlined />
                网络设备
              </Space>
            }
            extra={
              <Button type="link" icon={<EditOutlined />} disabled>
                编辑
              </Button>
            }
          >
            <Descriptions column={1}>
              <Descriptions.Item label="网络 1">default</Descriptions.Item>
              <Descriptions.Item label="设备模型">virtio</Descriptions.Item>
              <Descriptions.Item label="MAC 地址">
                52:54:00:xx:xx:xx
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>

        {/* 显示设备 */}
        <Col span={12}>
          <Card title="显示设备">
            <Descriptions column={1}>
              <Descriptions.Item label="类型">VNC</Descriptions.Item>
              <Descriptions.Item label="监听地址">127.0.0.1</Descriptions.Item>
              <Descriptions.Item label="端口">5900</Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>

        {/* 控制台设备 */}
        <Col span={12}>
          <Card title="控制台设备">
            <Descriptions column={1}>
              <Descriptions.Item label="类型">pty</Descriptions.Item>
              <Descriptions.Item label="目标类型">serial</Descriptions.Item>
              <Descriptions.Item label="目标端口">0</Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>
      </Row>

      {/* CPU 编辑模态框 */}
      <Modal
        title="编辑 CPU 配置"
        open={cpuModalVisible}
        onCancel={() => setCpuModalVisible(false)}
        onOk={() => form.submit()}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleUpdateCPU}
          initialValues={{ vcpus: domain.vcpus }}
        >
          <Form.Item
            label="虚拟 CPU 数量"
            name="vcpus"
            rules={[
              { required: true, message: '请输入 CPU 数量' },
              { type: 'number', min: 1, max: 32, message: '范围: 1-32' },
            ]}
          >
            <InputNumber min={1} max={32} style={{ width: '100%' }} />
          </Form.Item>

          <div style={{ color: '#999', fontSize: '12px' }}>
            注意：修改 CPU 配置需要关闭虚拟机后才能生效。
          </div>
        </Form>
      </Modal>

      {/* 内存编辑模态框 */}
      <Modal
        title="编辑内存配置"
        open={memoryModalVisible}
        onCancel={() => setMemoryModalVisible(false)}
        onOk={() => form.submit()}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleUpdateMemory}
          initialValues={{ memory: domain.memory }}
        >
          <Form.Item
            label="内存大小 (MB)"
            name="memory"
            rules={[
              { required: true, message: '请输入内存大小' },
              { type: 'number', min: 512, max: 65536, message: '范围: 512MB-64GB' },
            ]}
          >
            <InputNumber
              min={512}
              max={65536}
              step={512}
              style={{ width: '100%' }}
              addonAfter="MB"
            />
          </Form.Item>

          <div style={{ color: '#999', fontSize: '12px' }}>
            当前值: {(domain.memory / 1024).toFixed(1)} GB
            <br />
            最大值: {(domain.max_memory / 1024).toFixed(1)} GB
            <br />
            注意：修改内存配置需要关闭虚拟机后才能生效。
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default HardwareTab;
